<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>微信授权示例</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
        }
        .user-info {
            margin-top: 20px;
            padding: 15px;
            border: 1px solid #eee;
            border-radius: 8px;
            background-color: #f9f9f9;
        }
        .loading {
            color: #666;
            font-style: italic;
        }
    </style>
</head>
<body>
    <h1>微信授权</h1>
    
    <div id="authStatus" class="loading">
        正在检查微信授权状态...
    </div>
    
    <div id="userInfo" class="user-info" style="display: none;">
        <h3>用户信息</h3>
        <p>OpenID: <span id="openId"></span></p>
        <p>昵称: <span id="nickname"></span></p>
        <p>头像: <img id="avatar" style="width: 50px; height: 50px; border-radius: 50%;"></p>
    </div>

    <script>
        // 你的工具函数
        function isWechatBrowser() {
            return /MicroMessenger/i.test(navigator.userAgent);
        }

        function redirectToAuth() {
                
            const appId = 'wx0d6fd6596e1e4b49';
            // 注意：redirect_uri需要是公众号后台配置的域名下的地址
            const redirectUri = encodeURIComponent(`${window.location.origin}${window.location.pathname}`);
            const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
            window.location.href = authUrl;
            
        }

        function parseAuthCode() {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get('code');
        }

        // 获取用户信息
        async function getUserInfo(code) {
            try {
              
                const response = await fetch(`/api/wechat/auth?code=${code}`);
                const data = await response.json();
           
                if (data.success) {
                    // 存储openId
                    localStorage.setItem('wechat_openid', data.openid||'123');
                    return data;
                } else {
                    throw new Error('获取用户信息失败');
                }
            } catch (error) {
                console.error('获取用户信息失败:', error);
                throw error;
            }
        }

        // 获取用户详细信息（需要access_token）
        async function getUserDetail(openid, access_token) {
            try {
                const response = await fetch(`https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`);
                return await response.json();
            } catch (error) {
                console.error('获取用户详细信息失败:', error);
                return null;
            }
        }

        // 显示用户信息
        function displayUserInfo(user) {
            document.getElementById('authStatus').style.display = 'none';
            document.getElementById('userInfo').style.display = 'block';
            document.getElementById('openId').textContent = user.openid;
            document.getElementById('nickname').textContent = user.nickname || '未知';
            document.getElementById('avatar').src = user.headimgurl || '';
        }

        // 初始化检查
        document.addEventListener('DOMContentLoaded', async () => {
            console.log(4111);
            
             localStorage.setItem('wechat_openid','123');
            const authStatus = document.getElementById('authStatus');
            
            if (!isWechatBrowser()) {
                authStatus.textContent = '请在微信浏览器中打开此页面';
                return;
            }

            // 检查是否已有openId
            const openid = localStorage.getItem('wechat_openid')||'123';
            if (openid) {
                authStatus.textContent = '已授权，正在加载用户信息...';
                // 这里可以显示已存储的用户信息或获取最新信息
                displayUserInfo({ openid });
                return;
            }

            // 解析URL中的code
            const code = parseAuthCode();
            if (code) {
                try {
                    authStatus.textContent = '正在获取用户信息...';
                    
                    // 1. 获取openId和access_token
                    const authData = await getUserInfo(code);
                    
                    // 2. 获取用户详细信息
                    const userDetail = await getUserDetail(authData.openid, authData.access_token);
                    
                    // 3. 显示用户信息
                    displayUserInfo(userDetail);
                    
                    // 4. 清除URL中的code参数
                    window.history.replaceState({}, document.title, window.location.pathname);
                } catch (error) {
                    authStatus.textContent = '授权失败，请重试';
                    console.error('授权流程错误:', error);
                }
            } else {
                // 没有code，需要重定向授权
                redirectToAuth();
            }
        });
    </script>
</body>
</html>